import { createStore } from 'vuex';
import socket from '../socket';
// import boardsStore from './initProject'
// import recentProjectsStore from './recentProject'

const store = createStore({
  state() {
    return {
      ProjectsDir:null,
      selectFramework: null,
      boardData:[],
      recentProjectslist:[],
      storage:{},
    };
  },
  mutations: {
    fetchRecentProjectslist(state, value) {
      state.recentProjectslist = [...value];
    },
    fetchBoardsData(state, boardData) {
      state.boardData = [...boardData];
    },
    setSelectFramework(state, framework) {
      state.selectFramework = framework || '';
    },
    setProjectsDir(state, ProjectsDir) {
      state.ProjectsDir = ProjectsDir || '';
    },
    setStorage(state, storage) {
      state.storage = storage || {};
    },
    add_Recent_Project(state, projectPath) {
      // 确保 storage 和 recentProjects 是存在的
      if (!state.storage) {
        state.storage = {};
      }
      if (!Array.isArray(state.storage.recentProjects)) {
        state.storage.recentProjects = [];
      }
  
      // 防止重复添加同一项目
      if (!state.storage.recentProjects.includes(projectPath)) {
        state.storage.recentProjects.push(projectPath);
      }
    },
  },
  actions: {
    //异步代码
    asyncFetchBoardsData(store) {
      try {
        socket.emit('boards_json')
        socket.on('boards_json', (res) => {
          if (res.error) {
            console.error(res.error);
          } else {
            // console.log(res);
            let items = res;
            items = items.map((item) => {
              item.frameworks = item.frameworks || [];
              return item;
            });
            // console.log(items);
            store.commit('fetchBoardsData', items);
          }
        });
      } catch (err) {
        console.error(err);
      }
    },
    
    asyncSetProjectsDir(store) {
      try {
        socket.emit('load_state');
        socket.on('load_state',(res) => {
          if (res.error) {
            console.error(res.error);
          } else {
            // console.log(res.storage);
            store.commit('setStorage', res.storage);
            store.commit('setProjectsDir', res.storage.projectsDir);
          }
        });
      } catch (err) {
        console.error(err);
      }
    },

    asyncFetchRecentProjectsList(store) {
      try {       
          socket.emit('get_projects');
          socket.on('get_projects',(res) => {
            if (res.error) {
              console.error(res.error);
            } else {
              // console.log(Array.isArray(res));
              // console.log(res);
              // console.log(res[0].boards[0].id);
              store.commit('fetchRecentProjectslist', res); // 提交到 Vuex 中
            }
          })
      } catch (err) {
        console.error(err);
      }
    },
  },

  modules: {
    // boardsStore,
    // recentProjectsStore
  }
});


export default store